// pages/home/particulars/index.js
import {
  home
} from "../../../../../api/index.js";
const util = require('../../../../../utils/util')
const app = getApp();
const KEYOBJ = {
  "0": 'getcontentdetail',
  "1": 'getschooldetail',
  "2": 'getgoldenspikedetail'
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    JoinType: 0,
    imgDraw: null, //绘制图片的大对象
    sharePath: '',
    navObjWid: app.globalData.navObjWid,
    IMGBASEURL: app.globalData.IMGBASEURL,
    topDistance: "",
    bottomDistance: "",
    id: "",
    imgUrl: "",
    particularsData: {},
    swiperList: [],
    params: {},
    describe: "",
    lableList: [],
    current: 1, //轮播图当前页数
    rectRight: 0,
    navTop: "",
    navHeight: 0,
    isFollow: false,
    pageType: "",
    winWidth: 0,
    imgHightandWith: {},
    OriginalImgHightandWith: {},
    //评论数据
    PageIndex: 1,
    PageSize: 10,
    ID: "",
    loading: false, //是否正在加载数据
    commentList: [],
    TotalCount: 1,
    isActivity: false,
    DailyMyVote: 0,
    VoteCount: 0,
    CanVote: false,
    swiperHeaght: 0
  },
  onClick(even) {
    let key = even.currentTarget.dataset.key
    let current = even.currentTarget.dataset.url
    wx.previewImage({
      current, // 当前显示图片的http链接
      urls: this.data[key], // 需要预览的图片http链接列表
    });
  },

  toOthersPage() {
    if (!wx.getStorageSync('token')) {
      this.shudLogin();
      return
    }
    wx.navigateTo({
      url: `/pages/my/othersPage/index?code=${this.data.params.UserCode}`,
    });
  },
  tou() {
    if (!this.data.CanVote) return
    wx.showLoading()
    home.votecontent({
      ID: this.data.params.ID
    }).then(res => {
      if (res.StatusCode == 200) {
        this.setData({
          DailyMyVote: this.data.DailyMyVote + 1,
          VoteCount: this.data.VoteCount + 1
        })
        if (this.data.DailyMyVote >= this.data.params.CreationMax) {
          this.setData({
            CanVote: false
          })
        }
        wx.hideLoading()
      }
      if (res.StatusCode == 400) {
        wx.hideLoading()
      }
      wx.showToast({
        title: res.Message,
        icon: 'none'
      })
    }).catch((err) => {
      wx.hideLoading()
      if (err.statusCode === 401) {
        this.shudLogin();
      }
    });
  },
  //返回上一级
  goBack() {
    if (this.data.pageType === "share") {
      wx.switchTab({
        url: "/pages/home/index",
      });
    } else {
      wx.navigateBack();
    }
  },
  // 改变swiper页码
  swiperChange(e) {
    const current = e.detail.current + 1; // 因为索引是从0开始的，所以需要加1
    this.setData({
      current,
    });
  },
  // 获取数据
  async getData() {
    wx.showLoading()
    let res = await home[KEYOBJ[this.data.JoinType]]({
      ID: this.data.id,
    });
    res.Result.MainContent = decodeURI(res.Result.MainContent)
    this.setData({
      params: res.Result,
      imgUrlList: res.Result.CreationPictures.map(e => e.Url),
      OriginalUrlimgUrlList: res.Result.CreationPictures.map(e => e.OriginalUrl),
      DailyMyVote: res.Result.DailyMyVote,
      VoteCount: res.Result.VoteCount,
      CanVote: !(res.Result.DailyMyVote >= res.Result.CreationMax)
    });
    const OriginalUrl = this.data.params.CreationPictures[0].OriginalUrl
    const imgHightandWith = await this.getImageHeight(this.data.params.CreationPictures[0].Url)
    const OriginalImgHightandWith = await this.getImageHeight(OriginalUrl ? OriginalUrl : `${this.data.IMGBASEURL}/qs.png`)
    this.setData({
      imgHightandWith,
      OriginalImgHightandWith
    });
    this.drawPic()
    this.checkFollow();
    this.getCommentData()
  },
  getImageHeight(src) {
    if (!src) return 0
    return new Promise((resolve) => {
      wx.getImageInfo({
        src,
        success: (res) => {
          //设置图片宽高比
          resolve({
            height: res.height,
            width: res.width
          })
        },
        fail() {
          resolve({
            height: 0,
            width: 0
          })
        }
      });
    })

  },
  // 点赞/取消点赞
  Ilike() {
    const _this = this;
    const obj = {
      LikeID: this.data.params.ID,
    };
    home[
        this.data.params.IsLike ? "removelikeformcontent" : "addlikeformcontent"
      ](obj)
      .then((res) => {
        if (res.StatusCode === 200) {
          const num = this.data.params.IsLike ?
            (this.data.params.LikeCount -= 1) :
            (this.data.params.LikeCount += 1);
          this.setData({
            "params.IsLike": !this.data.params.IsLike,
            "params.LikeCount": num,
          });
        }
      })
      .catch((err) => {
        if (err.statusCode === 401) {
          _this.shudLogin();
        } else {
          wx.showToast({
            title: "请稍后重试！",
            icon: "error",
          });
        }
      });
  },
  // 收藏、取消收藏
  Icollection() {
    const _this = this;
    const obj = {
      ContentID: this.data.params.ID,
    };
    home[
        this.data.params.IsCollect ?
        "removecollectionformcontent" :
        "addcollectionformcontent"
      ](obj)
      .then((res) => {
        if (res.StatusCode === 200) {
          const num = this.data.params.IsCollect ?
            (this.data.params.CollectCount -= 1) :
            (this.data.params.CollectCount += 1);
          this.setData({
            "params.IsCollect": !this.data.params.IsCollect,
            "params.CollectCount": num,
          });
        }
      })
      .catch((err) => {
        if (err.statusCode === 401) {
          _this.shudLogin();
        }
      });
  },
  // 去评论详情
  toCommentDetail() {
    wx.navigateTo({
      url: "/pages/home/commentDetail/index?ID=" + this.data.params.ID,
    });
  },
  //判断是否关注
  async checkFollow() {
    // 登录了才调用
    let _this = this;
    let token = wx.getStorageSync("token");
    if (token) {
      let res = await home.isfollowtouser({
        ID: _this.data.params.UserId,
      });
      this.setData({
        isFollow: res.Result,
      });
    }
  },
  //关注
  async Ifollow() {
    const _this = this;
    home[this.data.isFollow ? "removefollow" : "addfollow"]({
        ID: this.data.params.UserId,
      })
      .then((res) => {
        if (res.StatusCode === 200) {
          this.setData({
            isFollow: !_this.data.isFollow,
          });
          wx.showToast({
            title: _this.data.isFollow ? "关注成功" : "取关成功",
            mask: "true",
          });
        }
      })
      .catch((err) => {
        if (err.statusCode === 401) {
          _this.shudLogin();
        }
      });
  },
  //去登录
  shudLogin() {
    const popup = this.selectComponent("#popupid");
    popup.setData({
      visible: true,
      isNavBar: false,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onReady() {
    const _this = this;
    wx.getSystemInfo({
      success: (res) => {
        let systemInfo = wx.getSystemInfoSync();
        let info = wx.getMenuButtonBoundingClientRect();
        console.log(systemInfo.screenHeight);
        let query = wx.createSelectorQuery();
        query.select('.activit-content').boundingClientRect(rect => {
          let height = rect.height;
          _this.setData({
            navTop: res.statusBarHeight,
            navHeight: (info.top - systemInfo.statusBarHeight) * 2 + info.height,
            winWidth: res.windowWidth,
          });
          _this.setData({
            navTop: res.statusBarHeight,
            navHeight: (info.top - systemInfo.statusBarHeight) * 2 + info.height,
            winWidth: res.windowWidth,
            swiperHeaght: systemInfo.screenHeight - (this.data.navTop + this.data.navHeight) - height
          });
        }).exec();
      },
      fail(err) {
        console.log(err);
      },
    });

  },
  onLoad(options) {
    let obj
    if (options.hasOwnProperty('q') && options.q) {
      // 通过下面这步解码，可以拿到url的值
      const url = decodeURIComponent(options.q)
      // 对url中携带的参数提取处理
      obj = util.urlToObj(url)
    } else {
      obj = options
    }
    this.setData({
      id: obj.id,
      JoinType: obj.JoinType,
      pageType: obj.pageType
    }, () => {
      this.getData();
    })

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getCommentData()
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    let title = this.data.params.Title
    let imageUrl = this.data.sharePath
    return {
      title,
      imageUrl,
      path: `/pages/home/activityDetail/activityContent/workDetails/index?id=${this.data.id}&pageType=share&JoinType=${this.data.JoinType}`,
    };
  },

  //评论数据
  async getCommentData() {
    // 如果正在加载数据，则直接返回，避免重复加载
    if (this.data.loading) {
      return;
    }
    // 设置加载中的标志
    this.setData({
      loading: true,
    });
    if (this.data.commentList.length === this.data.TotalCount) {
      return
    }
    const {
      PageIndex,
      PageSize,
    } = this.data
    let res = await home.getfirstcomment({
      PageIndex,
      PageSize,
      ID: this.data.params.ID
    })
    res.Result.Datas.forEach(item => {
      // 设置每个一级评论下的二级评论数据的初始状态
      item.showSecondary = false
      item.secondaryCommentList = []
    })
    this.setData({
      commentList: this.data.commentList.concat(res.Result.Datas),
      TotalCount: res.Result.TotalCount,
      PageIndex: this.data.PageIndex + 1,
      loading: false
    })
  },
  // 海报生成完成
  onImgOK(e) {
    if (e.detail.path) {
      this.setData({
        sharePath: e.detail.path,
      })
    }
    wx.hideLoading()
  },
  // 绘图失败
  onImgErr(e) {
    wx.hideLoading()
    wx.showToast({
      title: '分享图绘制失败',
      icon: 'none'
    })
  },
  // 生成海报
  drawPic() {
    let UserName = this.data.params.UserName
    if (UserName?.length > 12) {
      UserName = UserName.substring(0, 12)
    }
    this.setData({
      imgDraw: {
        "width": "1000rpx",
        "height": "800rpx",
        "background": "#1A1A1A",
        "position": "relative",
        "views": [{
            "type": "image",
            "url": this.data.params.CreationPictures[0]?.Url,
            "css": {
              "width": "1000rpx",
              "height": "800rpx",
            }
          },
          {
            "type": "image",
            // "url": "https://staticimg.aiiiin.com/wxapp/fen-huodong.png",
            "url": this.data.params.AppletShareUrl,
            "mode": "widthFix",
            "css": {
              "width": "1000rpx",
              "height": "800rpx",
            }
          },
          {
            "type": "image",
            "url": this.data.params.UserHeader,
            "mode": "widthFix",
            "css": {
              "width": "130rpx",
              "height": "130rpx",
              "left": "60rpx",
              "bottom": "22rpx",
              "borderRadius": "65rpx"
            }
          },
          {
            "type": "text",
            "text": `我是[${UserName}],`,
            // "text": `我是[草图里374855213],`,
            "css": {
              "left": "210rpx",
              "bottom": "95rpx",
              "fontSize": "36rpx",
              "color": "#424242",
              "fontWeight": "bold"
            },
          },
          {
            "type": "text",
            "text": "请您帮我的作品投上一票!",
            "css": {
              "left": "210rpx",
              "bottom": "40rpx",
              "fontSize": "36rpx",
              "color": "#424242",
              "fontWeight": "bold"
            },
          },
        ]
      }
    })
  },
});